package com.allenz.forum.services.Impl;

import com.allenz.forum.common.AppResult;
import com.allenz.forum.common.ResultCode;
import com.allenz.forum.dao.UserMapper;
import com.allenz.forum.exception.ApplicationException;
import com.allenz.forum.model.User;
import com.allenz.forum.services.IUserService;
import com.allenz.forum.utils.MD5Util;
import com.allenz.forum.utils.StringUtil;
import com.allenz.forum.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Base64;
import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void createNormalUser(User user) {
        // 1. 非空校验
        if (user == null || StringUtil.isEmpty(user.getUsername())
            || StringUtil.isEmpty(user.getNickname())
                || StringUtil.isEmpty(user.getPassword())
                    || StringUtil.isEmpty(user.getSalt())){
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常 , 统一抛出 ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 2. 按用户名查询用户信息
        User existUser = userMapper.selectByUserName(user.getUsername());
        // 2.1 判断用户是否存在
        if (existUser != null){
            // 打印日志
            log.info(ResultCode.FAILED_USER_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }

        // 3. 新增用户流程 , 设置默认值
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        // 设置日期
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);
        // 插入数据库
        int raw = userMapper.insertSelective(user);
        if (raw != 1){
            // 打印日志
            log.info(ResultCode.FAILED_CREATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        // 打印日志
        log.info("新增用户成功! username = " + user.getUsername() + ".");
    }

    @Override
    public User selectByUserName(String username) {
        if (StringUtil.isEmpty(username)) {
            // 非空校验
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常 , 统一抛出 ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 返回查询结果
        return userMapper.selectByUserName(username);
    }

    @Override
    public User login(String username, String password) {
        // 1. 非空校验
        if (StringUtil.isEmpty(username) || StringUtil.isEmpty(password)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        // 2. 按用户名查询用户信息
        User existUser = userMapper.selectByUserName(username);
        // 3. 对查询信息进行非空校验
        if (existUser == null){
            // 打印日志
            log.info(ResultCode.FAILED_LOGIN.toString() + " username = " + username);
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        // 4. 检查失败登录次数
        int failedLoginAttempts = existUser.getFailedLoginAttempts();
        if (failedLoginAttempts >= 5) {
            // 达到失败登录次数上限，禁止用户登录
            log.warn(ResultCode.FAILED_LOGIN_BANNED_ACCOUNT.toString() + "用户 " + username + " 多次登录失败，请于10分钟后再尝试登录。");
            throw new ApplicationException(ResultCode.FAILED_LOGIN_BANNED_ACCOUNT.getMessage());
        }
        // 5. 对密码做校验
        String encryptPassword = MD5Util.md5Salt(password, existUser.getSalt());
        if (!encryptPassword.equals(existUser.getPassword())){
            log.warn(ResultCode.FAILED_LOGIN.toString() + " username = " + username);

            // 更新失败登录次数
            existUser.setFailedLoginAttempts(failedLoginAttempts + 1);
            userMapper.updateFailedLoginAttempts(existUser);

            throw new ApplicationException(ResultCode.FAILED_LOGIN.getMessage());
        }
        // 密码正确时重置失败登录次数
        existUser.setFailedLoginAttempts(0);
        userMapper.updateFailedLoginAttempts(existUser);
        log.info("欢迎" + username + " , 登录成功!");
        return existUser;
    }

    @Override
    public User selectById(Long id) {
        // 1. 非空校验
        if (id == null){
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常 , 统一抛出 ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 调用DAO查询数据库并获取对象
        User user = userMapper.selectByPrimaryKey(id);
        // 返回结果
        return user;
    }

    @Override
    public void addOneArticleCountById(Long id) {
        if (id == null || id <= 0){
            // 打印日志
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        // 查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null){
            log.warn(ResultCode.ERROR_IS_NULL.toString() + " , user id = " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        // 更新发布的帖子数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() + 1);
        // 更新数据库
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1){
            log.warn(ResultCode.FAILED.toString() + " , 受影响的行数不等于1.");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        if (id == null || id <= 0){
            // 打印日志
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        // 查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null){
            log.warn(ResultCode.ERROR_IS_NULL.toString() + " , user id = " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        // 更新发布的帖子数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() - 1);
        // 判断减1后是否小于0
        if (updateUser.getArticleCount() < 0){
            // 如果小于0 则设置为0
            updateUser.setArticleCount(0);
        }
        // 更新数据库
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1){
            log.warn(ResultCode.FAILED.toString() + " , 受影响的行数不等于1.");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyInfo(User user) {
        // 非空校验
        if (user == null || user.getId() == null || user.getId() <= 0){
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 校验用户是否存在
        User existsUser = userMapper.selectByPrimaryKey(user.getId());
        if (existsUser == null){
            // 打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        // 定义一个标志位
        boolean checkAttr = false; // 表示没有校验通过

        // 定义一个专门用来更新的对象,防止用户传入的user对象设置了其他属性
        // 方使用动态SQL进行更新的时候,覆盖了没有经过校验的字段
        User updateUser = new User();

        // 设置用户id
        updateUser.setId(user.getId());

        // 对每一个参数进行校验并赋值
        if (!StringUtil.isEmpty(user.getUsername())
                && !existsUser.getUsername().equals(user.getUsername())){
            // 需要更新用户名(登录名)时 , 需要进行唯一性的校验
            User checkUser = userMapper.selectByUserName(user.getUsername());
            if (checkUser != null){
                // 用户已存在
                // 打印日志
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
                // 抛出异常
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
            }

            // 数据库中没有找到相应的用户名 , 可以修改
            updateUser.setUsername(user.getUsername());
            // 更新标志位
            checkAttr = true;
        }
        // 校验昵称
        if (!StringUtil.isEmpty(user.getNickname())
                && !user.getNickname().equals(existsUser.getNickname())){
            // 设置昵称
            updateUser.setNickname(user.getNickname());
            // 更新标志位
            checkAttr = true;
        }
        // 校验性别
        if (user.getGender() != null && existsUser.getGender() != user.getGender()){
            // 设置性别
            updateUser.setGender(user.getGender());
            // 合法性校验
            if (updateUser.getGender() < 0 || updateUser.getGender() > 2){
                updateUser.setGender((byte) 2);
            }
            // 更新标志位
            checkAttr = true;
        }
        // 校验email
        if (!StringUtil.isEmpty(user.getEmail())
                && !user.getEmail().equals(existsUser.getEmail())){
            // 设置email
            updateUser.setEmail(user.getEmail());
            // 更新标志位
            checkAttr = true;
        }
        // 校验电话
        if (!StringUtil.isEmpty(user.getPhoneNum())
                && !user.getPhoneNum().equals(existsUser.getPhoneNum())){
            // 设置电话号码
            updateUser.setPhoneNum(user.getPhoneNum());
            // 更新标志位
            checkAttr = true;
        }
        // 校验个人简介
        if (!StringUtil.isEmpty(user.getRemark())
                && !user.getRemark().equals(existsUser.getRemark())){
            // 设置个人简介
            updateUser.setRemark(user.getRemark());
            // 更新标志位
            checkAttr = true;
        }

        // 根据标志位判断是否执行更新
        if (checkAttr == false){
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 调用DAO
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1){
            log.warn(ResultCode.FAILED.toString() + " , 受影响的行数不等于1.");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        // 非空校验
        if (id == null || id <= 0 || StringUtil.isEmpty(newPassword) || StringUtil.isEmpty(oldPassword)){
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 根据id查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        // 校验用户是否存在
        if (user == null){
            // 打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        // 校验老密码是否正确
        // 对老密码进行加密 , 获取密文
        String oldEncryptPassword = MD5Util.md5Salt(oldPassword , user.getSalt());
        // 与用户的当前密码进行比较
        if (!oldEncryptPassword.equals(user.getPassword())){
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 生成一个盐值
        String salt = UUIDUtil.UUID_32();
        // 生成新密码的密文
        String encryptPassword = MD5Util.md5Salt(newPassword , salt);
        // 构造要更新的对象
        User updateUser = new User();
        updateUser.setId(user.getId()); // 用户id
        updateUser.setSalt(salt); // 新生成的盐
        updateUser.setPassword(encryptPassword); // 新密码对应的密文
        Date date = new Date();
        updateUser.setUpdateTime(date); // 更新时间

        // 调用 DAO
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1){
            log.warn(ResultCode.FAILED.toString() + " , 受影响的行数不等于1.");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }
    //存储背景图片
    @Override
    public void saveImage(Long userId, MultipartFile file) {
        try {
            byte[] base64Image = FileToBase64(file);
            if(base64Image == null) {
                log.warn(ResultCode.FAILED.toString() + " 图片为空！");
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
            }
            redisTemplate.opsForValue().set(String.valueOf(userId), base64Image);
        } catch (IOException e) {
            log.error("Error converting file to base64", e);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }

    }

    public byte[] FileToBase64(MultipartFile file) throws IOException {
        return file.getBytes();
    }

    public byte[] getBackgroundImageFromDatabase(Long id){
        String Id = id.toString();
        return (byte[]) redisTemplate.opsForValue().get(Id);

    }
}

























